package com.mnt.washio.utils.network.ws;

import java.io.IOException;
import java.util.LinkedHashMap;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;

import com.mnt.washio.utils.Statics;
import com.mnt.washio.utils.network.NetworkUtils;
import com.mnt.washio.utils.network.WebServiceCommunicatorListener;

@SuppressLint("DefaultLocale")
public class ApplyCouponWSControl extends BaseWSControl {
	String userId;
	String couponCode;

	public ApplyCouponWSControl(Context context,
			WebServiceCommunicatorListener listener, String userId,
			String couponCode) {
		super(context, listener, WebServiceFlag.APPLY_COUPON);
		this.userId = userId;
		this.couponCode = couponCode.toLowerCase();
	}

	@Override
	protected Object doInBackground(Void... params) {
		// Get local database

		String url = Statics.WASHIO_WS_URL + "coupon/apply";
		LinkedHashMap<String, String> parameters = new LinkedHashMap<String, String>();
		parameters.put("couponCode", couponCode);
		parameters.put("userId", userId);
		try {
			String respone = NetworkUtils.doPostRequest(url, parameters);
			return parseResult(respone);

		} catch (ClientProtocolException e) {
			mError = "Cannot connect to network";
			e.printStackTrace();
		} catch (IOException e) {
			mError = "Cannot connect to network";
			e.printStackTrace();
		}
		return null;
	}

	private Boolean parseResult(String json) {
		try {
			JSONObject jsonObject = new JSONObject(json);
			if (jsonObject.has("error")) {
				mError = jsonObject.getString("error");
				return null;
			}
			else if(jsonObject.has("coupon")){
				return jsonObject.getBoolean("coupon");
			}
			return null;
		} catch (Exception e) {
			mError = e.getMessage();
			return null;
		}
	}

}
